package dfs_bfs;

import java.util.LinkedList;
import java.util.Queue;

public class lc1020 {
    public static void main(String[] args) {
        System.out.println(numEnclaves_bfs(new int[][]{{0,0,0,0},{1,0,1,0},{0,1,1,0},{0,0,0,0}}));
    }


    public static int numEnclaves_bfs(int[][] grid) {
        int sum = 0;
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < grid.length; i++) {
            if(grid[i][0] == 1)
                queue.add(new int[]{i, 0});
            if(grid[i][grid[0].length - 1] == 1)
                queue.add(new int[]{i, grid[0].length - 1});
        }
        for (int i = 0; i < grid[0].length; i++) {
            if(grid[0][i] == 1)
                queue.add(new int[]{0, i});
            if(grid[grid.length - 1][i] == 1)
                queue.add(new int[]{grid.length - 1, i});
        }
        while( !queue.isEmpty()){
            int[] temp = queue.poll();
            int i = temp[0], j = temp[1];
            if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0)
                continue;
            grid[i][j] = 0;
            queue.add(new int[]{i + 1, j});
            queue.add(new int[]{i - 1, j});
            queue.add(new int[]{i, j - 1});
            queue.add(new int[]{i, j + 1});
        }
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 1)
                    sum += 1;
            }
        }
        return sum;
    }

    public static int numEnclaves(int[][] grid) {
        int sum = 0;
        for (int i = 0; i < grid.length; i++) {
            dfs(grid, i, 0);
            dfs(grid, i, grid[0].length - 1);
        }
        for (int i = 0; i < grid[0].length; i++) {
            dfs(grid, 0, i);
            dfs(grid, grid.length - 1, i);
        }
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 1){
                    sum += 1;
                }
            }
        }
        return sum;
    }
    public static void dfs(int[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {
            return;
        }
        grid[i][j] = 0;
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }
}
